/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package boxync;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Daniel Ginting
 */
public class BoxyncSecurity {
    public DESKeySpec keySpec;
    public SecretKeyFactory keyFact;
    public SecretKey key;
    public sun.misc.BASE64Encoder enc;
    public sun.misc.BASE64Decoder dec;
    
    public BoxyncSecurity() {
        try {
            keySpec = new DESKeySpec("badumtss".getBytes("UTF8"));
            keyFact = SecretKeyFactory.getInstance("DES");
            key = keyFact.generateSecret(keySpec);
            enc = new BASE64Encoder();
            dec = new BASE64Decoder();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
    
    public String encrypt(String pass) {
        String value = "";
        byte[] cleartext;
        Cipher cipher;
        
        try {
            cleartext = pass.getBytes("UTF8");
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            value = enc.encode(cipher.doFinal(cleartext));
        } catch (Exception uee) {
            System.err.println(uee.getMessage());
        }
        
        return value;
    }
    
    public String decrypt(String encptpwd) {
        String value = "";
        byte[] encptpwdBytes;
        Cipher cipher;
        
        try {
            encptpwdBytes = dec.decodeBuffer(encptpwd);
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            value = new String(cipher.doFinal(encptpwdBytes));
        } catch (Exception uee) {
            System.err.println(uee.getMessage());
        }
        return value;
    }
}